//
//  AXHandler.h
//  AssionX
//
//  Created by Coldwinter on 13-10-14.
//
//

#ifndef __AssionX__AXHandler__
#define __AssionX__AXHandler__

#include <iostream>
#include <queue>


#include <cocos2d.h>
#include <pthread.h>


using namespace cocos2d;
using namespace std;

/**
 * similar to android.os.Handler
 * used for post message to different thread
 * this is thread safe
 **/
typedef struct _message
{
    int what;
    int arg1,arg2;
    void* obj;
    _message(int what):
    what(what),
    arg1(0),
    arg2(0),
    obj(NULL)
    {
    }
    
    _message(){}
}Message;
// define the type for callback function 
typedef void (CCObject::*SEL_Handler)(Message);
#define selector_handler(_SELECTOR) (SEL_Handler)(&_SELECTOR)

class AXHandler:public CCObject
{
public:

    static AXHandler* create();

    virtual bool init();
    
    virtual ~AXHandler();
    /**
    * override autorelease method,
    * in case 2dx released it without calling 'cleanup'
    **/
    virtual CCObject* autorelease();
    // post a message
    void postMessage(Message);
    // post a message with only one arg 'what'
    void postEmptyMessage(int);
    // set a callback func
    void setCallback(CCObject*,SEL_Handler);
    // meke the message queue empty
    void clear();
    // mast call this method before release it
    void cleanup();
protected:
    // avoid new a instance outter
    AXHandler();
    // message queue
    queue<Message> m_msg_queue;
    // mutex lock
    pthread_mutex_t m_msg_mutex;
    // callback func and target
    CCObject* m_target;
    SEL_Handler m_selector;
    // recv the message and dispach it
    void onDispachMessage(float delta);
};

#endif /* defined(__AssionX__AXHandler__) */
